<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8"
          ><el-input
            placeholder="请输入内容"
            v-model="selectUser"
            class="input-with-select"
            :clearable="true"
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="search"
            ></el-button> </el-input
        ></el-col>
        <el-col :span="4"
          ><el-button type="primary" @click="addUser">添加用户</el-button>
        </el-col>
      </el-row>

      <template>
        <el-table :data="UserList" border stripe>
          <el-table-column prop="username" label="用户名" width="140">
          </el-table-column>
          <el-table-column prop="email" label="邮箱" width="140">
          </el-table-column>
          <el-table-column prop="mobile" label="电话" width="140">
          </el-table-column>
          <el-table-column prop="role_name" label="身份"> </el-table-column>
          <el-table-column label="状态">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.mg_state"
                @change="editUserState(scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="200">
            <template slot-scope="scope">
              <el-tooltip content="修改用户" placement="top" :enterable="false">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="editUser(scope.row.id)"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="分配角色" placement="top" :enterable="false">
                <el-button
                  size="mini"
                  type="warning"
                  icon="el-icon-share"
                  @click="editRight(scope.row)"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="删除用户" placement="top" :enterable="false">
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="delUser(scope.row.id)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <!-- 添加用户表单 -->
      <el-dialog
        title="添加用户"
        :visible.sync="addVisible"
        width="30%"
        @close="removeForm('addUserFormRef')"
      >
        <el-form
          label-position="left"
          label-width="80px"
          :model="addUserForm"
          :rules="addRules"
          ref="addUserFormRef"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUserForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addUserForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="addUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUserVisible">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 分配角色 -->

      <el-dialog
        title="分配角色"
        :visible.sync="Rolevisible"
        width="30%"
        @close="clearRole"
      >
        <div>
          <p>当前用户:{{ this.RoleInfo.username }}</p>
          <p>当前角色:{{ this.RoleInfo.role_name }}</p>

          <el-select v-model="RoleInfo.roleid" placeholder="请选择">
            <el-option
              v-for="item in RoleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="Rolevisible = false">取 消</el-button>
          <el-button type="primary" @click="distributionRole">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改用户表单 -->
      <el-dialog
        title="修改用户"
        :visible.sync="editVisible"
        width="30%"
        @close="removeForm('editUserFormRef')"
      >
        <el-form
          label-position="left"
          label-width="80px"
          :model="editUserForm"
          :rules="editRules"
          ref="editUserFormRef"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editUserForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="editUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUserVisible">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagenum"
      :page-sizes="[2, 4, 6, 8]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
  </div>
</template>

<script>
export default {
  data() {
    var validateEmail = (rule, value, callback) => {
      var emailReg = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
      if (emailReg.test(value)) {
        callback();
      } else {
        callback(new Error("请输入正确的邮箱格式"));
      }
    };

    var validateMobile = (rule, value, callback) => {
      var phoneReg = /^1[345789]\d{9}$/;
      if (phoneReg.test(value)) {
        callback();
      } else {
        callback(new Error("请输入正确的手机格式"));
      }
    };
    return {
      Rolevisible: false,
      UserList: [],
      selectUser: "",
      pagenum: 1,
      pagesize: 2,
      total: 10,
      RoleList: [],
      addVisible: false,
      state: true,
      //添加用户表单
      addUserForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      //角色信息
      RoleInfo: {
        username: "",
        role_name: "",
        roleid: null,
        userid: null,
      },
      //修改用户表单
      editUserForm: {
        id: 0,
        username: "",
        email: "",
        mobile: "",
      },
      editVisible: false,

      //添加用户表单验证
      addRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 11, message: "请输入3到11个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 12, message: "请输入6到12个字符", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: validateEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机", trigger: "blur" },
          { validator: validateMobile, trigger: "blur" },
        ],
      },

      //修改用户表单验证
      editRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 11, message: "请输入3到11个字符", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: validateEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机", trigger: "blur" },
          { validator: validateMobile, trigger: "blur" },
        ],
      },
    };
  },
  mounted() {
    this.getUserList();
    // console.log(this.$refs.editUserFormRef);
      // console.log(this.$refs,12333333);

  },
  methods: {
    eddddd(val) {
      console.log(val, "新状态的值");
      this.state = val;
    },
    //点击添加用户
    addUser() {
      this.addVisible = true;
    },

    //点击确定添加用户
    addUserVisible() {
      // console.log(this.$refs,1323);
      this.$refs.addUserFormRef.validate(async (validate) => {
        if (validate) {
          const { data: res } = await this.$axios.post(
            "users",
            this.addUserForm
          );
          if (res.meta.status === 201) {
            this.$message.success("添加用户成功");
            this.getUserList();
            this.addVisible = false;
          } else {
            this.$message.error("添加用户失败");
          }
        }
      });
    },

    //取消按钮时,重置表单
    removeForm(RefName) {
      this.$refs[RefName].resetFields();
    },

    // 获取用户列表
    async getUserList() {
      const { data: res } = await this.$axios.get("users", {
        params: {
          pagenum: this.pagenum,
          pagesize: this.pagesize,
        },
      });
      this.total = res.data.total;
      this.UserList = res.data.users;
      // console.log(res);
    },

    //修改用户状态
    async editUserState(user) {
      console.log(user.mg_state);
      const { data: res } = await this.$axios.put(
        `users/${user.id}/state/${user.mg_state}`
      );
      if (res.meta.status === 200) {
        return this.$message.success("修改状态成功");
      }
      this.$message.error("修改状态失败");
      user.mg_state = !user.mg_state;
    },

    //通过用户名搜索用户
    async search() {
      this.pagenum = 1;
      const { data: res } = await this.$axios.get("users", {
        params: {
          query: this.selectUser,
          pagenum: this.pagenum,
          pagesize: this.pagesize,
        },
      });
      this.total = res.data.total;
      this.UserList = res.data.users;
    },

    //修改用户信息
    async editUser(id) {
      this.editUserForm.id = id;
      const { data: res } = await this.$axios.get("users/" + id);
      this.editUserForm = res.data;

      this.editVisible = true;
    },

    //点击确定修改用户信息
    editUserVisible() {
      this.$refs.editUserFormRef.validate(async (valida) => {
        console.log(valida);
        if (valida) {
          const { data: res } = await this.$axios.put(
            "users/" + this.editUserForm.id,
            {
              email: this.editUserForm.email,
              mobile: this.editUserForm.mobile,
            }
          );

          if (res.meta.status === 200) {
            this.$message.success("修改用户信息成功");
            this.getUserList();
            this.editVisible = false;
          }
        }
      });
    },

    //分配角色权限
    async editRight(row) {
      this.RoleInfo.userid = row.id;
      this.RoleInfo.username = row.username;
      this.RoleInfo.role_name = row.role_name;
      const { data: res } = await this.$axios.get("roles");
      console.log(res);
      this.RoleList = res.data;
      this.Rolevisible = true;
    },

    //点击确定分配角色
    async distributionRole() {
      const { data: res } = await this.$axios.put(
        "users/" + this.RoleInfo.userid + "/role",
        {
          rid: this.RoleInfo.roleid,
        }
      );
      if (res.meta.status == 200) {
        this.$message.success("用户修改角色成功");
        this.getUserList();
      }
      console.log(this.RoleInfo.roleid, this.RoleInfo.userid);
      this.Rolevisible = false;
    },

    //清除分配角色信息
    clearRole() {},

    //删除用户
    async delUser(id) {
      // console.log(id);
      const flag = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      if (flag === "confirm") {
        const { data: res } = await this.$axios.delete("users/" + id);
        // console.log(res)
        if (res.meta.status === 200) {
          this.$message.success("删除用户成功");
          this.getUserList();
        }
      } else {
        this.$message.info("你取消了删除操作");
      }
    },

    //pageSize改变时触发
    handleSizeChange(val) {
      this.pagesize = val;
      this.getUserList();
    },

    //当前页码改变时触发
    handleCurrentChange(val) {
      this.pagenum = val;
      this.getUserList();
    },
  },
};
</script>

<style scope></style>
